<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use App\Utils\CustomUtils;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
// use Hyperf\HttpServer\Contract\ResponseInterface;
use App\Exception\XZXValidationException;
// use Phper666\JWTAuth\Exception\JWTException;
use Phper666\JWTAuth\Exception\TokenValidException;
use Hyperf\HttpMessage\Exception\UnauthorizedHttpException;
use Throwable;
use Hyperf\Utils\Codec\Json;
// use App\Utils\XZXResponse;
use App\Constants\XZXResponseCode;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        // $this->logger->error($throwable->getTraceAsString());
        // return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));

        $ret = [
            'code'    => $throwable->getCode(),
            'message' => $throwable->getMessage(),
            'data'    => CustomUtils::xzxEmptyObject(),

            'error' => sprintf('(%s) %s', get_class($throwable), $throwable->getMessage()),
            'file'  => sprintf('At %s line %d', $throwable->getFile(), $throwable->getLine()),
            //             'trace' => $e->getTraceAsString(), // trace 太长了
        ];

        $statusCode = XZXResponseCode::INTERNAL_CODE;

        if (!env('APP_DEV',0)) {
            unset($ret['error']);
            unset($ret['file']);
        }

        switch (true) {
            // case $throwable instanceof TokenValidException:
            // case $throwable instanceof JWTException:
            case $throwable instanceof UnauthorizedHttpException:
            case $throwable instanceof XZXValidationException:
            case $throwable instanceof TokenValidException:
            case $throwable instanceof Throwable:
                $statusCode = XZXResponseCode::REQUEST_SUCCESS_CODE;
                $ret['message'] = $throwable->getMessage();
                break;
            default:
                // $response = $response->withStatus(500);
                break;
        }

        if ($ret['code'] == XZXResponseCode::SUCCESS_CODE) {
            $ret['code'] = XZXResponseCode::FAILED_CODE;
        }

        $this->stopPropagation();
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8')
                        ->withStatus($statusCode)
                        ->withBody(new SwooleStream(json::encode($ret)));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
